import axios from 'axios'

// create an axios instance
const service = axios.create({
	headers: {
		'content-type': 'application/json;charset=UTF-8',
	},
	baseURL: 'http://localhost:7777', // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent
		// let each request carry token
		// ['token'] is a custom headers key
		// please modify it according to the actual situation
		
		// 判断该请求是否要携带token
		// isToken(0表示需要token 1表示不需要token)
		const isToken = config.headers.isToken === "0"
		let token = "";
		uni.getStorage({
			key: 'token',
			success: function (res) {
				token = res.data;
			}
		});
		
		if(isToken && token != ""){
			config.headers['token'] = token
		}
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)


// response interceptor
service.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	 */

	/**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code
	 */
	res => {
		const code = res.data.code;
		if(code == 401){
			uni.navigateTo({
				url:"/pages/login/index"
			})
		}
		return res.data;
	}
)

export default service